package cn.haoma.base.utils;

import android.os.Handler;
import android.os.Message;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by ilioili on 2015/6/24.
 * 倒计时工具
 */
public class CountdownUtil {
    private CallBack callBack;
    private int current;
    private boolean isPuuse;
    private Timer timer;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (!isPuuse) {
                current--;
                if (current < 0) {
                    timer.cancel();
                    callBack.onFinish();
                } else {
                    callBack.onDick(current);
                }

            }
        }
    };
    private TimerTask timerTask;
    private int total;

    public CountdownUtil(int total, CallBack callBack) {
        this.total = total;
        this.callBack = callBack;
    }

    public void pause() {
        isPuuse = true;
    }

    public void restart() {
        current = total;
        if (timer != null) {
            timer.cancel();
        }
        start();
    }

    public void start() {
        isPuuse = false;
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0);
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

    public void resume() {
        isPuuse = false;
    }

    public void stop() {
        isPuuse = false;
        if (null != timer) {
            timer.cancel();
            callBack.onFinish();
        }
    }

    public interface CallBack {
        void onDick(int current);

        void onFinish();
    }


}
